#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

Myfile* buyMyfile(int fd, int flag)
{
    Myfile* file = (Myfile*)malloc(sizeof(Myfile));
    if(file == NULL)
    {
        return NULL;
    }
    file->fileno = fd;
    file->flag = flag;
    file->bufferLen = 0;
    memset(file->buffer, 0, sizeof(file->buffer));
    file->fflush_mode = LINE_FFLUSH;
    
    return file; 
}


Myfile* myFopen(const char* path, const char* mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "r") == 0)
    {
        flag =O_RDONLY;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }
    else 
    {
        // todo
    }

    if(fd < 0) return NULL;
    return buyMyfile(fd, flag);
}
void myFclose(Myfile* file)
{
    myFflush(file);
    close(file->fileno);
    free(file);
}
int myFwrite(const void* ptr, size_t len, Myfile* file)
{
    // 拷贝到用户级缓冲区中
    memcpy(file->buffer + file->bufferLen, ptr, len);
    file->bufferLen += len;

    // 尝试判断是否满足刷新条件
    if(file->fflush_mode == LINE_FFLUSH && file->buffer[file->bufferLen - 1] == '\n')
    {
        myFflush(file);
    }

    return 0;
}
void myFflush(Myfile* file)
{
    if(file->bufferLen <= 0) return;
    write(file->fileno, file->buffer, file->bufferLen);

    fsync(file->fileno);
    file->bufferLen = 0;
}
